package com.hjyang.word.convert.pdf.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
    private final static Logger stringUtilLogger = LoggerFactory.getLogger(StringUtil.class);
    private static Pattern linePattern = Pattern.compile("_(\\w)");
    private static Pattern humpPattern = Pattern.compile("[A-Z]");
    
    /**
     * 判断是否为手机号
     *
     * @param str
     * @return 中国移动号码：134、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188
     * 中国联通号码：130、131、132、155、156、176、185、186
     * 中国电信号码：133、153、180、181、189、173、177
     * 虚拟运营商：170
     */
    public static boolean isChinaPhoneLegal(String str) {
        String regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0,3,6-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
    
    /**
     * 生成随机字符串
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    
    /**
     * 下划线转驼峰
     *
     * @param str
     * @return
     */
    public static String lineToHump(String str) {
        if (null == str || "".equals(str)) {
            return str;
        }
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        
        str = sb.toString();
        str = str.substring(0, 1).toUpperCase() + str.substring(1);
        
        return str;
    }
    
    /**
     * 驼峰转下划线(简单写法，效率低于{@link #humpToLine2(String)})
     *
     * @param str
     * @return
     */
    public static String humpToLine(String str) {
        return str.replaceAll("[A-Z]", "_$0").toLowerCase();
    }
    
    /**
     * 驼峰转下划线,效率比上面高
     *
     * @param str
     * @return
     */
    public static String humpToLine2(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
    
    
    public static String getSpanHtml(String value) {
        String html = "";
        String[] valTemp = value.split(",");
        if (valTemp.length > 0) {
            for (int i = 0; i < valTemp.length; i++) {
                html += "<span>" + valTemp[i] + "</span>";
            }
        } else {
            html = "<span>" + value + "</span>";
        }
        return html;
    }
    
    /**
     * object转String
     *
     * @param object
     * @return
     */
    public static String getString(Object object) {
        return getString(object, "");
    }
    
    public static String getString(Object object, String defaultValue) {
        if (null == object) {
            return defaultValue;
        }
        try {
            return object.toString();
        } catch (Exception e) {
            return defaultValue;
        }
    }
    
    /**
     * @param value
     * @return
     */
    public static boolean isEmpty(CharSequence value) {
        if (value == null || value.length() == 0) {
            return true;
        }
        
        return false;
    }
    
    /**
     * object转Integer
     *
     * @param object
     * @return
     */
    public static int getInt(Object object) {
        return getInt(object, -1);
    }
    
    public static int getInt(Object object, Integer defaultValue) {
        if (null == object) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(object.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }
    
    /**
     * object转Boolean
     *
     * @param object
     * @return
     */
    public static boolean getBoolean(Object object) {
        return getBoolean(object, false);
    }
    
    public static boolean getBoolean(Object object, Boolean defaultValue) {
        if (null == object) {
            return defaultValue;
        }
        try {
            return Boolean.parseBoolean(object.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }
    
    /**
     * @param b 字节数组
     * @return 16进制字符串
     * @throws
     * @Title:bytes2HexString
     * @Description:字节数组转16进制字符串
     */
    public static String bytes2HexString(byte[] b) {
        StringBuffer result = new StringBuffer();
        String hex;
        for (int i = 0; i < b.length; i++) {
            hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            result.append(hex.toUpperCase());
        }
        return result.toString();
    }
    
    /**
     * @param src 16进制字符串
     * @return 字节数组
     * @throws
     * @Title:hexString2Bytes
     * @Description:16进制字符串转字节数组
     */
    public static byte[] hexString2Bytes(String src) {
        int l = src.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            ret[i] = (byte) Integer
                                    .valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
        }
        return ret;
    }
    
    /**
     * @param strPart 字符串
     * @return 16进制字符串
     * @throws
     * @Title:string2HexString
     * @Description:字符串转16进制字符串
     */
    public static String string2HexString(String strPart) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < strPart.length(); i++) {
            int ch = (int) strPart.charAt(i);
            String strHex = Integer.toHexString(ch);
            hexString.append(strHex);
        }
        return hexString.toString();
    }
    
    /**
     * @param src 16进制字符串
     * @return 字节数组
     * @throws
     * @Title:hexString2String
     * @Description:16进制字符串转字符串
     */
    public static String hexString2String(String src) {
        String temp = "";
        for (int i = 0; i < src.length() / 2; i++) {
            temp = temp
                           + (char) Integer.valueOf(src.substring(i * 2, i * 2 + 2),
                    16).byteValue();
        }
        return temp;
    }
    
    /**
     * @param src
     * @return
     * @throws
     * @Title:char2Byte
     * @Description:字符转成字节数据char-->integer-->byte
     */
    public static Byte char2Byte(Character src) {
        return Integer.valueOf((int) src).byteValue();
    }
    
    /**
     * @param a   转化数据
     * @param len 占用字节数
     * @return
     * @throws
     * @Title:intToHexString
     * @Description:10进制数字转成16进制
     */
    private static String intToHexString(int a, int len) {
        len <<= 1;
        String hexString = Integer.toHexString(a);
        int b = len - hexString.length();
        if (b > 0) {
            for (int i = 0; i < b; i++) {
                hexString = "0" + hexString;
            }
        }
        return hexString;
    }
    
    
    /**
     * URL字符串转化成Map
     *
     * @param param
     * @return
     */
    public static Map<String, Object> getUrlParams(String param) {
        Map<String, Object> mapUrl = new Hashtable<String, Object>();
        if ("".equals(param) || null == param) {
            return mapUrl;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            if (params[i].contains("username=")) {
                mapUrl.put("username", params[i].replace("username=", ""));
            } else if (params[i].contains("MAIN_ID=")) {
                mapUrl.put("MAIN_ID", params[i].replace("MAIN_ID=", ""));
            } else if (params[i].contains("ticket=")) {
                mapUrl.put("ticket", params[i].replace("ticket=", ""));
            }
        }
        return mapUrl;
    }
    
    /**
     * 返回option字符串
     *
     * @return
     */
    public static String returnOption(String optionstr) {
        String reoptionstr = "";
        String[] option = optionstr.split("@");
        for (int i = 0; i < option.length; i++) {
            reoptionstr += "<option value=\"" + option[i].substring(0, option[i].indexOf("#")) + "\">" + option[i].substring(option[i].indexOf("#") + 1, option[i].length()) + "</option>";
        }
        return reoptionstr;
    }
    
    public static int getSum(String str1, String str2, String str3, String str4, String str5, String str6, String str7, String str8) {
        int count = StringUtil.StringToInt(StringUtil.null2String(str1))
                            + StringUtil.StringToInt(StringUtil.null2String(str2))
                            + StringUtil.StringToInt(StringUtil.null2String(str3))
                            + StringUtil.StringToInt(StringUtil.null2String(str4))
                            + StringUtil.StringToInt(StringUtil.null2String(str5))
                            + StringUtil.StringToInt(StringUtil.null2String(str6))
                            + StringUtil.StringToInt(StringUtil.null2String(str7))
                            + StringUtil.StringToInt(StringUtil.null2String(str8));
        return count;
    }
    
    public static String getUTF8FromISO(String str) {
        String outStr = "";
        try {
            outStr = new String(str.getBytes("iso-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return outStr;
    }
    
    
    /**
     * 将ISO字符转化为GBK字符
     *
     * @param str
     */
    public static String getGBKFromISO(String str) {
        try {
            if (str == null) {
                str = "";
            }
            byte[] buf = str.getBytes("iso-8859-1");
            byte[] buf2 = str.getBytes("gbk");
            if (!str.equals(new String(buf2, "gbk"))) {
                str = new String(buf, "gbk");
            }
            
            return str;
        } catch (UnsupportedEncodingException e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return str;
    }
    
    //从URL中将UTF8转换为GBK
    public static String getGBKFromURL(String s) {
        String ret = "null";
        try {
            ret = java.net.URLDecoder.decode(s, "utf-8");
        } catch (UnsupportedEncodingException ex) {
        }
        return ret;
    }
    
    //从URL中将GBK转换为UTF8
    public static String getUTFFromURL(String s) {
        String ret = "null";
        try {
            ret = URLEncoder.encode(s, "utf-8");
        } catch (UnsupportedEncodingException ex) {
        }
        return ret;
    }
    
    public static String getGBKFromUTF(String str) {
        try {
            if (str == null) {
                str = "";
            }
            byte[] buf = str.getBytes("utf-8");
            byte[] buf2 = str.getBytes("gbk");
            if (!str.equals(new String(buf2, "gbk"))) {
                str = new String(buf, "gbk");
            }
            
            return str;
        } catch (UnsupportedEncodingException e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return str;
    }
    
    
    /**
     * 将列表转换为字符串输出
     *
     * @param arr
     * @param split
     */
    @SuppressWarnings("rawtypes")
    public static String getStrByArray(ArrayList arr, String split) {
        String outstr = "";
        for (int i = 0; i < arr.size(); i++) {
            outstr += arr.get(i) + split;
        }
        if (outstr.length() > 0) {
            outstr = outstr.substring(0, outstr.length() - 1);
        }
        return outstr;
    }
    
    /**
     * 将GBK字符转化为ISO字符
     *
     * @param str
     */
    public static String getISOFromGBK(String str) {
        try {
            if (str == null) {
                str = "";
            }
            byte[] buf = str.getBytes("gbk");
            byte[] buf2 = str.getBytes("iso-8859-1");
            if (!str.equals(new String(buf2, "iso-8859-1"))) {
                str = new String(buf, "iso-8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return str;
    }
    
    /**
     * 将字符串handleStr中以pointStr以分隔的每个字符串存放在向量中返回
     *
     * @param handleStr
     * @param pointStr
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static Vector explode(String handleStr, String pointStr) {
        Vector v = new Vector();
        int pos1, pos2;
        try {
            if (handleStr.length() > 0) {
                pos1 = handleStr.indexOf(pointStr);
                pos2 = 0;
                while (pos1 != -1) {
                    v.addElement(handleStr.substring(pos2, pos1));
                    pos2 = pos1 + pointStr.length();
                    pos1 = handleStr.indexOf(pointStr, pos2);
                }
                v.addElement(handleStr.substring(pos2));
            }
        } catch (Exception e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return v;
    }
    
    /**
     * 在字符串handleStr中的字符串pointStr以repStr代替
     *
     * @param handleStr
     * @param pointStr
     * @param repStr
     */
    public static String replace(String handleStr, String pointStr, String repStr) {
        if (null == handleStr) {
            return "";
        }
        String str = new String();
        int pos1, pos2;
        try {
            if (handleStr.length() > 0) {
                pos1 = handleStr.indexOf(pointStr);
                pos2 = 0;
                while (pos1 != -1) {
                    str += handleStr.substring(pos2, pos1);
                    str += repStr;
                    pos2 = pos1 + pointStr.length();
                    pos1 = handleStr.indexOf(pointStr, pos2);
                }
                str += handleStr.substring(pos2);
            }
        } catch (Exception e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return str;
    }
    
    
    public static String getStringSplit(String allStr, String regex, int index) {
        String returnStr = "";
        if ("".equals(allStr) || allStr == null || "null".equals(allStr)) {
            returnStr = "";
        } else {
            String str[] = allStr.split(regex);
            if (str.length >= index) {
                returnStr = str[index];
            }
        }
        
        return returnStr;
    }
    
    
    /**
     * 将字符串中的"\n"以"<br>&nbsp;&nbsp;" 替换后返回
     *
     * @param handleStr
     */
    public static String returnChar2BR(String handleStr) {
        String str = handleStr;
        str = replace(str, "\n", "<br>&nbsp;&nbsp;");
        return str;
    }
    
    
    /**
     * 将字符串中的"\n"以"<br>&nbsp;&nbsp;" 替换后返回
     *
     * @param handleStr
     */
    public static String returnChar2BRno(String handleStr) {
        String str = handleStr;
        if (str != null) {
            str = replace(str, "\n", "<br>");
        } else {
            str = "";
        }
        return str;
    }
    
    /**
     * 将handler中的内容取出转换为字符串并将其每个以separator分割开后返回。
     *
     * @param handler
     * @param separator
     */
    @SuppressWarnings("rawtypes")
    public static String implode(Vector handler, String separator) {
        StringBuffer strbuf = new StringBuffer();
        try {
            if (!handler.isEmpty()) {
                int len = handler.size();
                for (int loopi = 0; loopi < len; loopi++) {
                    strbuf.append((String) handler.get(loopi));
                    if (loopi != len - 1) {
                        strbuf.append(separator);
                    }
                }
            }
        } catch (Exception e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return strbuf.toString();
    }
    
    /**
     * Return appointed String from a String Vector
     * param1: String Vector
     * param2: appointed Index
     * param3: include Excel CSV process.
     */
    @SuppressWarnings("rawtypes")
    public static String getField(Vector vt, int i, boolean isExcel) {
        String str = "";
        try {
            str = (String) vt.get(i);
            if (str != null && str.length() > 2 && isExcel) {
                if (str.substring(0, 1).compareTo("\"") == 0) {
                    str = str.substring(1, str.length() - 1);
                    str = StringUtil.replace(str, "\"\"", "\"");
                }
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
            return "";
        }
        return str;
    }
    
    /**
     * 当字符串长度小于Len时，有字符InsChar填冲到str的左边或右边，当intDirect为0时为左，1时为右
     * param1: father string
     * param2: need fill in char
     * param3: 0 is left fill in
     * 1 is right fill in
     * param4: total string length after fill in char
     */
    public static String insStr(String str, String InsChar, int intDirect,
                                int Len) {
        int intLen = str.length();
        StringBuffer strBuffer = new StringBuffer(str);
        
        if (intLen < Len) {
            int inttmpLen = Len - intLen;
            for (int i = 0; i < inttmpLen; i++) {
                if (intDirect == 1) {
                    str = str.concat(InsChar);
                } else if (intDirect == 0) {
                    strBuffer.insert(0, InsChar);
                    str = strBuffer.toString();
                }
            }
        }
        return str;
    }
    
    /**
     * 返回在字符串str中，首次出现字符串divided的位置。若没有找到返回-1
     *
     * @param str
     * @param divided
     */
    public static int searchDiv(String str, String divided) {
        try {
            divided = divided.trim();
            int divpos = -1;
            
            if (str.length() > 0) {
                divpos = str.indexOf(divided);
                
                return divpos;
            } else {
                return divpos;
            }
        } catch (Exception e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
            return -1;
        }
    }
    
    /**
     * 在字符串str中取首次出现startdiv到首次出现enddiv之间的字符串并返回，如果没有找到返回“”
     *
     * @param str
     * @param startdiv
     * @param enddiv
     */
    public static String extractStr(String str, String startdiv, String enddiv) {
        int startdivlen = startdiv.length();
        str = str.trim();
        
        int startpos = -1;
        int endpos = -1;
        
        startdiv = startdiv.trim();
        enddiv = enddiv.trim();
        startpos = searchDiv(str, startdiv);
        if (str.length() > 0) {
            if (startpos >= 0) {
                str = str.substring(startpos + startdivlen);
                str = str.trim();
            }
            endpos = searchDiv(str, enddiv);
            if (endpos == -1) {
                return "";
            }
            str = str.substring(0, endpos);
            str = str.trim();
        }
        return str;
    }
    
    /**
     * 返回一个不为空的字符串
     *
     * @param str
     */
    public static String isNull(String str) {
        return isNull(str, "&nbsp;");
    }
    
    /**
     * 返回一个不为空的字符串，当为空时返回def
     *
     * @param str
     * @param def
     */
    public static String isNull(String str, String def) {
        if (str == null) {
            return def;
        } else if (str.length() == 0) {
            return def;
        } else {
            return str;
        }
    }
    
    /**
     * 将字符串类型转换为整数类型
     *
     * @param str
     */
    public static int StringToInt(String str) {
        return StringToInt(str, 0);
    }
    
    /**
     * 将字符串类型转换为整数类型，出错时有def值返回
     *
     * @param str
     * @param def
     */
    public static int StringToInt(String str, int def) {
        int intRet = def;
        try {
            if (str == null || "".equals(str.trim())) {
                str = def + "";
            }
            intRet = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return intRet;
    }
    
    /**
     * 将字符串类型转换为浮点类型
     *
     * @param str
     */
    public static float StringToFloat(String str) {
        return StringToFloat(str, 0);
    }
    
    /**
     * 将字符串类型转换为浮点类型，出错时有def值返回
     *
     * @param str
     * @param def
     */
    public static float StringToFloat(String str, float def) {
        float fRet = def;
        try {
            if (str == null || "".equals(str.trim())) {
                str = "0";
            }
            fRet = Float.parseFloat(str);
        } catch (NumberFormatException e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
            return def;
        }
        return fRet;
    }
    
    /**
     * 将字符串类型转换为双精度类型
     *
     * @param str
     */
    public static double StringToDouble(String str) {
        return StringToDouble(str, (double) 0);
    }
    
    /**
     * 将字符串类型转换为双精度类型，出错时有def值返回
     *
     * @param str
     * @param def
     */
    public static double StringToDouble(String str, double def) {
        double dRet = (double) def;
        try {
            if (str == null || "".equals(str.trim())) {
                str = "0";
            }
            dRet = Double.parseDouble(str);
        } catch (NumberFormatException e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return dRet;
    }
    
    /**
     * 将字符串类型转换为双精度类型
     *
     * @param str
     */
    public static long StringToLong(String str) {
        return StringToLong(str, (long) 0);
    }
    
    /**
     * 将字符串类型转换为双精度类型，出错时有def值返回
     *
     * @param str
     * @param def
     */
    public static long StringToLong(String str, long def) {
        long dRet = (long) def;
        try {
            if (str == null || "".equals(str.trim())) {
                str = "0";
            }
            dRet = Long.parseLong(str);
        } catch (NumberFormatException e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return dRet;
    }
    
    /**
     * 获得安全字符串，使得字符串不为空，并去掉前后的空格
     *
     * @param str
     */
    public static String getSafeString(String str) {
        if (str == null) {
            return "";
        } else {
            return str.trim();
        }
    }
    
    /**
     * 将字符串在指定的长度内显示，超出后以..代替
     *
     * @param str  in string
     * @param iLen specify length
     *             out string
     */
    public static String substr(String str, int iLen) {
        if (str == null) {
            return "";
        }
        if (iLen > 2) {
            if (str.length() > iLen - 2) {
                str = str.substring(0, iLen - 2) + "..";
            }
            
        }
        return str;
    }
    
    /**
     * 截取指定长度字符串
     *
     * @param str
     * @param iLen
     * @return
     * @author WLY
     * @日期 2013-7-31 上午5:44:16
     */
    public static String substrByLen(String str, int iLen) {
        if (str == null) {
            return "";
        }
        int len = str.length();
        if (len >= iLen) {
            return str.substring(0, iLen);
        }
        return str;
    }
    
    public static String substr(String oldString, int length, String add) {
        int oldL = oldString.length();
        if (oldL < length) {
            for (int i = 0; i < (length - oldL); i++) {
                oldString += add;
            }
        } else if (oldL > length) {
            oldString = oldString.substring(0, 8);
        }
        return oldString;
    }
    
    /**
     * 将字符串转换为UTF-8
     *
     * @param str handle string
     *            str
     */
    public static String getJpString(String str) {
        if (str == null) {
            return null;
        }
        try {
            return new String(str.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return null;
    }
    
    /**
     * 将字符串数组转换为UTF-8
     *
     * @param str handle string
     *            str[]
     */
    
    public static String[] getJpString(String[] str) {
        if (str == null) {
            return null;
        }
        String[] ret = new String[str.length];
        for (int i = 0; i < str.length; i++) {
            ret[i] = getJpString(str[i]);
        }
        return ret;
    }
    
    /**
     * 返回以UTF-8编码的URL
     *
     * @param str handle string
     *            str[]
     */
    
    public static String getUrlString(String str) {
        if (str == null) {
            return null;
        }
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
        }
        return null;
    }
    
    /**
     * 将对象转换了字符型
     *
     * @param s
     */
    public static String null2String(Object s) {
        return s == null || "null".equals(s) || "NULL".equals(s) ? "" : s.toString();
    }
    
    /**
     * 运行可执行文件
     *
     * @param cmd
     * @return String
     */
    public static synchronized boolean executeCmd(String cmd) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
        } catch (Exception e) {
            stringUtilLogger.error("StringUtil类出现异常", e);
            return false;
        }
        process.destroy();
        return true;
    }
    
    
    /**
     * 将字符串数组转换为（'a','b'）的格式后返回，来方便数据库的操作
     *
     * @param names
     * @return String
     */
    public static String getStrsplit(String[] names) {
        if (names == null || names.length == 0) {
            return "('')";
        }
        String result = "(";
        for (int i = 0; i < names.length; i++) {
            if (i == names.length - 1) {
                result = result + "'" + names[i] + "'";
            } else {
                result = result + "'" + names[i] + "',";
            }
        }
        result = result + ")";
        return result;
    }
    
    /**
     * 将字符串数组转换为（'a','b'）的格式后返回，来方便数据库的操作
     *
     * @param names
     * @return String
     */
    @SuppressWarnings("rawtypes")
    public static String getStrsplit(ArrayList names) {
        if (names == null || names.size() == 0) {
            return "('')";
        }
        String result = "(";
        for (int i = 0; i < names.size(); i++) {
            if (i == names.size() - 1) {
                result = result + "'" + (String) names.get(i) + "'";
            } else {
                result = result + "'" + (String) names.get(i) + "',";
            }
        }
        result = result + ")";
        return result;
    }
    

    
    /**
     * 将整型数组转换为（1，2）的格式后返回，来方便数据库的操作
     *
     * @param ids
     * @return String
     */
    public static String getIdsplit(String[] ids) {
        if (ids == null || ids.length == 0) {
            return "('')";
        }
        String result = "(";
        for (int i = 0; i < ids.length; i++) {
            if (i == ids.length - 1) {
                result = result + ids[i];
            } else {
                result = result + ids[i] + ",";
            }
        }
        result = result + ")";
        return result;
    }
    
    /**
     * 将向量转换为（1，2）的格式后返回，来方便数据库的操作
     *
     * @param ids
     * @return String
     */
    @SuppressWarnings("rawtypes")
    public static String getIdsplit(ArrayList ids) {
        if (ids == null || ids.size() == 0) {
            return "('')";
        }
        String result = "(";
        for (int i = 0; i < ids.size(); i++) {
            if (i == ids.size() - 1) {
                result = result + (String) ids.get(i);
            } else {
                result = result + (String) ids.get(i) + ",";
            }
        }
        result = result + ")";
        return result;
    }
    
    public static String getStringByStringList(String[] StringList) {
        if (StringList == null || StringList.length == 0) {
            return "";
        }
        String result = "";
        for (int i = 0; i < StringList.length; i++) {
            if (i == StringList.length - 1) {
                result = result + StringList[i];
            } else {
                result = result + StringList[i] + ",";
            }
        }
        return result;
    }
    
    /**
     * 将字符串数组转换为（'a','b'）的格式后返回，来方便数据库的操作
     *
     * @param names
     * @return String
     */
    @SuppressWarnings("rawtypes")
    public static String getStrByArr(ArrayList names, String split) {
        if (names == null || names.size() == 0) {
            return "";
        }
        String result = "";
        for (int i = 0; i < names.size(); i++) {
            if (i == names.size() - 1) {
                result += names.get(i) + "";
            } else {
                result = names.get(i) + split;
            }
        }
        return result;
    }
    
    /**
     * 将字符串数组转换为（'a','b'）的格式后返回，来方便数据库的操作
     *
     * @param names
     * @return String
     */
    public static String getStrByArr(String names[], String split) {
        if (names == null || names.length == 0) {
            return "";
        }
        String result = "";
        for (int i = 0; i < names.length; i++) {
            if (i == names.length - 1) {
                result += names[i] + "";
            } else {
                result = names[i] + split;
            }
        }
        return result;
    }
    
    /**
     * 将url转换为图片的HTML代码格式
     *
     * @param url
     * @return String
     */
    public static String toImage(String url) {
        return "<img src='" + url + "' border=0>";
    }
    
    /**
     * 将url转换为图片的HTML代码格式
     *
     * @param url
     * @return String
     */
    public static String toImage(String url, String attribute) {
        return "<img src='" + url + "' border=0 " + attribute + " >";
    }
    
    /**
     * 返回树形结构的字符串为├来分级
     *
     * @param level
     * @param flag
     * @return String
     */
    public static String getLevelFlag(int level, String flag) {
        String temp = "";
        for (int i = 0; i < level; i++) {
            temp = temp + flag;
        }
        return temp + "├";
    }
    
    
    public static String getValues(String str) {
        if (str == null || "".equals(str)) {
            return "0";
        }
        return str;
    }
    
    public static int getStrLen(String str) {
        if (str == null || "".equals(str)) {
            return 0;
        }
        return str.length();
    }
    
    public static String getParentID(String str) {
        if (str == null || "".equals(str) || str.length() == 4) {
            return "0000";
        }
        return str.substring(0, str.length() - 4);
    }
    
    //截取字符串
    public static String getSubStirng(String str, int start, int len) {
        if (str.length() >= len) {
            return str.substring(start, len);
        } else {
            return "";
        }
    }
    
    //获得字符串长度
    public static int getStringlen(String str) {
        return str.length();
    }
    
    
    //判断用户的 角色中是否有某个id
    
    /**
     * add by  amshren 2013年4月9日10:59:30
     *
     * @param roleList
     * @param roleid
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static boolean isRolein(List roleList, String roleid) {
        String role[] = new String[roleList.size()];// 所有的角色id
        for (int i = 0; i < roleList.size(); i++) {
            if (!"".equals(StringUtil.null2String(roleList.get(i)))) {
                role[i] = StringUtil.null2String(roleList.get(i));
                
                if (roleid.equals(role[i])) {
                    return true;
                }
            }
        }
        return false;
    }
    
    
    public static String getStrFromStrs(String Strs, String regex, int index) {
        if ("".equals(Strs) || null == Strs) {
            return "";
        } else {
            String Results[] = Strs.split(regex);
            if (Results.length > index) {
                return Results[index];
            } else {
                return "";
            }
        }
    }
    
    /**
     * add By amshren 2013年4月16日13:23:58
     *
     * @param ht  对象集合的Hashtable
     * @param str 对象在Hashtable中的主键
     * @return 返回对应主键的出现异常的时候值 默认返回&nbsp;
     */
    
    @SuppressWarnings("rawtypes")
    public static String getTableStringFromHT(Hashtable ht, String str) {
        String returnStr = "";
        if (str == null || "".equals(str) || "".equals(str)
                    || ht.get(str) == null) {
            returnStr = "&nbsp;";
        } else {
            returnStr = (String) ht.get(str);
        }
        return returnStr;
    }
    
    /**
     * add By amshren 2013年4月16日13:23:58
     *
     * @param ht         对象集合的Hashtable
     * @param str        对象在Hashtable中的主键
     * @param defaultStr 默认返回值
     * @return 返回对应主键的出现异常的时候值 默认返回defaultStr;
     */
    @SuppressWarnings("rawtypes")
    public static String getTableStringFromHT(Hashtable ht, String str, String defaultStr) {
        String returnStr = "";
        if (str == null || "".equals(str) || "".equals(str)
                    || ht.get(str) == null) {
            returnStr = defaultStr;
        } else {
            returnStr = (String) ht.get(str);
        }
        return returnStr;
    }
    
    /**
     * add By amshren 2013年4月16日13:23:58
     *
     * @param ht  对象集合的Hashtable
     * @param str 对象在Hashtable中的主键
     * @return 返回对应主键的出现异常的时候值 默认返回""
     */
    @SuppressWarnings("rawtypes")
    public static String getNoNullStringFromHT(Hashtable ht, String str) {
        String returnStr = "";
        if (str == null || "".equals(str) || "".equals(str)
                    || ht.get(str) == null) {
            returnStr = "";
        } else {
            returnStr = (String) ht.get(str);
        }
        return returnStr;
    }
    
    public static String getTableString(String str) {
        String returnStr = "&nbsp;";
        if (str != null && !"".equals(str) && !"null".equals(str)) {
            returnStr = str;
        }
        return returnStr;
    }
    
    
    /**
     * 将编码转换成对应的名称以便前台显示
     *
     * @param
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static String StrKeyToValue(Hashtable HT, String key, String regex, String returnRegex) {
        String returnStr = "";
        if (HT == null || key == null) {
            returnStr = "无";
        } else {
            String keys[] = key.split(regex);
            for (int i = 0; i < keys.length; i++) {
                String Str = null2String((String) HT.get(keys[i]));
                if ("".equals(returnStr)) {
                    returnStr = returnStr + ("".equals(Str) ? keys[i] : Str);
                } else {
                    returnStr = returnStr + returnRegex + ("".equals(Str) ? keys[i] : Str);
                }
            }
        }
        return returnStr;
    }
    
    
    /**
     * 判断 src是否包含  dst  常用于 页面判断
     *
     * @param src
     * @param dst
     * @return 若包含则返回下标，否则返回-1
     */
    public static int indexOf(String src, String dst) {
        return src.indexOf(dst);
    }
    
    
    /**
     * 字符串转换成数组
     */
    public static String[] getsplitStrs(String names, String str) {
        String[] result = null;
        try {
            names = null2String(names);
            result = names.split(str);
            
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 字符串转换为ArrayList
     *
     * @param names
     * @param str
     * @return
     */
    public static ArrayList getArrayListSplitStrs(String names, String str) {
        ArrayList arrayList = new ArrayList();
        try {
            names = null2String(names);
            if (!"".equals(names)) {
                String[] result = names.split(str);
                for (int i = 0; i < result.length; i++) {
                    arrayList.add(result[i]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arrayList;
    }
    
    /**
     * 字符串转换成数组
     */
    public static String getSplit(ArrayList ids) {
        if (ids == null || ids.size() == 0) {
            return "0";
        }
        String result = "";
        for (int i = 0; i < ids.size(); i++) {
            if (i == ids.size() - 1) {
                result = result + (String) ids.get(i);
            } else {
                result = result + (String) ids.get(i) + ",";
            }
        }
        return result;
    }
    
    /**
     * 字符串转换成数组
     */
    public static String getstrsplitStrs(String names, String str, int index) {
        String result = null;
        try {
            names = null2String(names);
            String[] results = names.split(str);
            if (results.length >= index) {
                result = results[index];
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 页面空值显示
     *
     * @param str
     * @return
     */
    public static String null2zero(Object str) {
        if (str == null || "".equals(null2String(str).trim()) || "null".equals(null2String(str).trim()) || "NULL".equals(null2String(str).trim())) {
            return "0";
        } else {
            return null2String(str);
        }
    }
    
    public static String StrtoStrbfh(String str) {
        DecimalFormat dec = new DecimalFormat("0.00");
        return dec.format(StringToFloat(str) * 100) + "%";
    }
    
    
    /**
     * 比较指定百分比值
     *
     * @param v1，制定的百分比值
     * @param v2，区间值1
     * @param v3，区间值2
     * @return
     */
    public static int CompareT_Decimal(String v1, String v2, String v3) {
        if ("-".equals(v1) || "-".equals(v2) || "-".equals(v3)) {
            return 0;
        } else {
            Double Dec_value1 = StringToDouble(v1.replace("%", ""));
            
            Double Dec_value2 = StringToDouble(v2.replace("%", ""));
            
            Double Dec_value3 = StringToDouble(v3.replace("%", ""));
            
            //在区间值内
            if (Dec_value1 < Dec_value2) {
                return 2;
            } else if (Dec_value1 > Dec_value2 && Dec_value1 < Dec_value3) {
                return 1;
            } else if (Dec_value1 > Dec_value3) {
                return 3;
            }
            
            return 0;
        }
    }
    
    /**
     * 获取两个值除以后的百分比
     *
     * @param v1
     * @param v2
     * @return
     */
    public static String Two_value_Decimal(String v1, String v2) {
        String Dec_value = "";
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(0);
        if ("0".equals(v2)) {
            return "0";
        } else {
            Dec_value = numberFormat.format(StringUtil.StringToFloat(v1) / StringUtil.StringToFloat(v2) * 100);
        }
        return Dec_value + "%";
    }
    
    /**
     * 获取两个值除以后的百分比
     *
     * @param v1
     * @param v2
     * @return
     */
    public static String Two_value_Decimal2(String v1, String v2) {
        String Dec_value = "";
        DecimalFormat df = new DecimalFormat(".00");
        if ("0".equals(v2) || "".equals(v2)) {
            return "-";
        } else {
            Dec_value = df.format(StringUtil.StringToDouble(v1) / StringUtil.StringToDouble(v2) * 100);
        }
        return Dec_value + "%";
    }
    
    
    /**
     * 通过LIST重新组合LIST内数据，以,隔开
     *
     * @param list
     * @param indexNo
     * @return
     */
    public static String getValueByIndex(List list, int indexNo) {
        String str = "";
        ArrayList sl = null;
        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                sl = (ArrayList) list.get(i);
                str += StringUtil.null2String(sl.get(indexNo)) + ",";
            }
        }
        if (!"".equals(str)) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }
    
    /**
     * 获取指标时间格式
     *
     * @param zbsj
     * @return
     * @author WLY
     * @日期 2014-5-11 下午8:00:17
     */
    public static String getZBSJ(String zbsj) {
        if (null == zbsj && "".equals(zbsj)) {
            return "";
        } else if (zbsj.length() == 4) {
            return zbsj + "年";
        } else if (zbsj.length() == 5) {
            return zbsj.substring(0, 4) + "年" + zbsj.substring(4, 5) + "季度";
        } else if (zbsj.length() == 6) {
            return zbsj.substring(0, 4) + "年" + zbsj.substring(4, 6) + "月份";
        }
        return "";
    }
    
    /**
     * 解析编码
     *
     * @param src
     * @return
     */
    public static String unescape(String src) {
        if (src == null) {
            return null;
        }
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src
                                                         .substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src
                                                         .substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }
    
    
    /**
     * 获取字符串中指定字符的数量
     *
     * @param str
     * @param tagStr
     * @param counter
     * @return
     */
    public static int stringNumbers(String str, String tagStr, int counter) {
        if ("".equals(null2String(tagStr))) {
            return counter;
        }
        if (str.indexOf(tagStr) == -1) {
            return counter;
        } else if (str.indexOf(tagStr) != -1) {
            counter++;
            return stringNumbers(str.substring(str.indexOf(tagStr) + tagStr.length()), tagStr, counter);
        }
        return counter;
    }
    
    /**
     * 替换字符串中逗号为换行符  \n 便于textarea 中显示
     *
     * @param handleStr
     * @return
     * @author WLY
     * @日期 2014-6-15 下午8:01:16
     */
    public static String returnChar2NR(String handleStr) {
        if (null == handleStr) {
            return "";
        }
        String str = handleStr;
        str = replace(str, ",", "\n");
        return str;
    }
    
    /**
     * 大于一万的数转化为万级单位显示
     *
     * @param str
     * @return
     */
    public static String converNum(String str) {
        double d = StringUtil.StringToDouble(str.trim());
        if (d > 10000) {
            double d1 = d / 10000;
            BigDecimal b = new BigDecimal(d1);
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            return f1 + "万";
        }
        return (int) d + "";
    }
    
    /**
     * 数字转化为%显示
     *
     * @param str
     * @return
     */
    public static String pnum2String(String str) {
        if (!"".equals(str)) {
            if ("0".equals(str)) {
                return "0";
            } else {
                double d = StringUtil.StringToDouble(str.trim());
                BigDecimal b = new BigDecimal(d);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                return f1 + "%";
            }
        } else {
            return "-";
        }
        
    }
    
    //格式化浮点数字========================
    
    /**
     * @param value
     * @param pattern "#"表示如果该位存在字符，则显示字符，如果不存在，则不显示。如："##000.000 kg";
     * @return
     */
    public static String format(Double value, String pattern) {
        DecimalFormat df = new DecimalFormat();
        df.applyPattern(pattern);
        return df.format(value);
    }
    
    public String formatD(String value, String pattern) {
        if ("".equals(value)) {
            value = "0";
        }
        return format(Double.valueOf(value), pattern);
    }
    
    /**
     * 浮点型数据格式化，防止小数点前的0丢失以及位数控制
     * </br>pattern前台输入示例：0.111111 表示最长六位小数，小数点后尾数是0的不显示
     *
     * @param value
     * @param pattern
     * @return
     * @author WLY
     * @日期 2014-5-21 下午7:09:20
     */
    public String formatD4html(String value, String pattern) {
        if ("".equals(null2String(value).trim())) {
            return "";
        }
        pattern = pattern.replace("1", "#");
        return format(Double.valueOf(value), pattern);
    }
    
    /**
     * 百分比格式化
     *
     * @param value
     * @param pattern
     * @return
     * @author WLY
     * @日期 2014-6-30 下午1:39:11
     */
    public String formatD4Percent(String value, String pattern) {
        if ("".equals(null2String(value).trim())) {
            return "";
        }
        if ("0".equals(null2String(value).trim())) {
            return "0";
        }
        pattern = pattern.replace("1", "#");
        return format(Double.valueOf(value) * 100, pattern) + "%";
    }
    //格式化浮点数字========================
    
    
    public String getTwoNumSum(String num1, String num2) {
        int n1 = StringToInt(num1);
        int n2 = StringToInt(num2);
        
        return "" + (n1 + n2);
    }
    
    /**
     * 层级显示前缀
     *
     * @param
     * @return
     * @author WLY
     * @日期 2014-7-17 下午2:21:21
     */
    public String getShowPrefix(String cjNum) {
        String line = "&nbsp;&nbsp;";
        String node = "&nbsp;├";
        String restr = "";
        int count = StringToInt(cjNum);
        for (int tmp = 1; tmp < count; tmp++) {
            restr += line;
        }
        return restr += node;
    }
    
    /**
     * 判断字符串是否为纯数字
     *
     * @param str
     * @return
     */
    public static boolean strisnum(String str) {
        boolean result = str.matches("[0-9]+");
        return result;
    }
    
    public static boolean ispointnum(String str) {
        return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
    }
    
    
    /**
     * 字节流转化为字符串
     *
     * @param in
     * @param charset 文件的字符集
     * @return
     * @author WLY
     * @日期 2014-12-18 下午4:58:32
     */
    public static String stream2String(InputStream in, String charset) {
        StringBuffer sb = new StringBuffer();
        Reader r = null;
        try {
            r = new InputStreamReader(in, charset);
            int length = 0;
            for (char[] c = new char[1024]; (length = r.read(c)) != -1; ) {
                sb.append(c, 0, length);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (r != null) {
                try {
                    r.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
    
    
    /**
     * 获取两个字符串的匹配数（相似度）
     *
     * @param strA
     * @param strB
     * @return 返回匹配百分比
     */
    public static double SimilarDegree(String strA, String strB) {
        String newStrA = removeSign(strA);
        String newStrB = removeSign(strB);
        int temp = Math.max(newStrA.length(), newStrB.length());
        int temp2 = longestCommonSubstring(newStrA, newStrB).length();
        return temp2 * 1.0 / temp;
    }
    
    private static String removeSign(String str) {
        StringBuffer sb = new StringBuffer();
        for (char item : str.toCharArray()) {
            if (charReg(item)) {
                sb.append(item);
            }
        }
        return sb.toString();
    }
    
    private static boolean charReg(char charValue) {
        return (charValue >= 0x4E00 && charValue <= 0X9FA5)
                       || (charValue >= 'a' && charValue <= 'z')
                       || (charValue >= 'A' && charValue <= 'Z')
                       || (charValue >= '0' && charValue <= '9');
    }
    
    private static String longestCommonSubstring(String strA, String strB) {
        char[] chars_strA = strA.toCharArray();
        char[] chars_strB = strB.toCharArray();
        int m = chars_strA.length;
        int n = chars_strB.length;
        int[][] matrix = new int[m + 1][n + 1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (chars_strA[i - 1] == chars_strB[j - 1]) {
                    matrix[i][j] = matrix[i - 1][j - 1] + 1;
                } else {
                    matrix[i][j] = Math.max(matrix[i][j - 1], matrix[i - 1][j]);
                }
            }
        }
        char[] result = new char[matrix[m][n]];
        int currentIndex = result.length - 1;
        while (matrix[m][n] != 0) {
            if (matrix[n] == matrix[n - 1]) {
                n--;
            } else if (matrix[m][n] == matrix[m - 1][n]) {
                m--;
            } else {
                result[currentIndex] = chars_strA[m - 1];
                currentIndex--;
                n--;
                m--;
            }
        }
        return new String(result);
    }
    
    
    /**
     * @param str
     * @param target
     * @return
     */
    private static int compare(String str, String target) {
        int d[][]; // 矩阵
        int n = str.length();
        int m = target.length();
        int i; // 遍历str的
        int j; // 遍历target的
        char ch1; // str的
        char ch2; // target的
        int temp; // 记录相同字符,在某个矩阵位置值的增量,不是0就是1
        if (n == 0) {
            return m;
        }
        if (m == 0) {
            return n;
        }
        d = new int[n + 1][m + 1];
        for (i = 0; i <= n; i++) { // 初始化第一列
            d[i][0] = i;
        }
        
        for (j = 0; j <= m; j++) { // 初始化第一行
            d[0][j] = j;
        }
        
        for (i = 1; i <= n; i++) { // 遍历str
            ch1 = str.charAt(i - 1);
            // 去匹配target
            for (j = 1; j <= m; j++) {
                ch2 = target.charAt(j - 1);
                if (ch1 == ch2) {
                    temp = 0;
                } else {
                    temp = 1;
                }
                // 左边+1,上边+1, 左上角+temp取最小
                d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + temp);
            }
        }
        return d[n][m];
    }
    
    private static int min(int one, int two, int three) {
        return (one = one < two ? one : two) < three ? one : three;
    }
    
    public static float getSimilarityRatio(String str, String target) {
        return 1 - (float) compare(str, target) / Math.max(str.length(), target.length());
    }
    
}
